package com.surfilter.job;

import com.google.gson.Gson;
import com.surfilter.gsxt.util.HttpRequestUtil;
import com.surfilter.pojo.GsxtTask;
import com.surfilter.thread.GsxtThread;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * ExecutorJob
 * Created by Grom on 2017/2/23.
 * 描述：
 * 定时任务，定时从持久层获取企业名录信息，爬取裁判文书信息
 */
public class ExecutorJob {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorJob.class);
    private boolean enable;
    private static int threadCount = Integer.parseInt(ResourceBundle.getBundle("system-config").getString("thread_count"));
    private static ExecutorService exes = Executors.newFixedThreadPool(threadCount);
    private static String crawlerUrl = ResourceBundle.getBundle("system-config").getString("crawler_url");

    public void work(){
        if(!this.isEnable()) return;
        if(isFull()) return;
        Executor();
    }

    private void Executor() {
        String str = HttpRequestUtil.sendPost(crawlerUrl,null);
        if(StringUtils.isNotBlank(str)){
            GsxtTask task = new Gson().fromJson(str,GsxtTask.class);
//            task.setCompanyName("一起生活网（大连）网络科技有限公司");
            String companyName = task.getCompanyName();
            if(companyName.length()>6){
                //初始化线程
                GsxtThread gsxtThread = new GsxtThread(task);
                exes.submit(gsxtThread);
                logger.info("企业："+companyName+"--->进入企业信用信息公示系统采集");
            }else{
                logger.info("companyName is too short,it may be a human name:" + companyName);
            }
        }else{
            logger.info("获取到任务为空");
        }
        logger.info("活跃线程数为："+((ThreadPoolExecutor) exes).getActiveCount());
    }
    public boolean isEnable() {
        return enable;
    }
    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public boolean isFull() {
        if(((ThreadPoolExecutor) exes).getActiveCount() == threadCount){
            logger.info("线程池满了。不继续进行创建任务");
            return true;
        }else{
            return false;
        }
    }
}
